package com.xc.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.xc.conf.ConfigurationManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReadDbByJDBC {
    private static DataSource dataSource;

    private static List<Connection> connectionList = new ArrayList<>();

    private static int num = 0;

    public static void init(String initialSize) {
        int initSizeInt = Integer.valueOf(initialSize);
        HashMap<String, String> config = new HashMap<>();
        config.put("driverClassName", ConfigurationManager.getProperty("jdbc.driver"));
        config.put("url", ConfigurationManager.getProperty("jdbc.url"));
        config.put("username", ConfigurationManager.getProperty("jdbc.username"));
        config.put("password", ConfigurationManager.getProperty("jdbc.password"));
        config.put("initialSize", initialSize);
        config.put("maxActive", initialSize);
        config.put("maxWait", ConfigurationManager.getProperty("jdbc.maxWait"));
        config.put("minIdle", initialSize);
        config.put("testOnBorrow", "false");

        try {
            dataSource = DruidDataSourceFactory.createDataSource(config);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < initSizeInt; i++) {
            try {
                Connection connection = dataSource.getConnection();
                connectionList.add(connection);
            } catch (SQLException sqlException) {
                sqlException.printStackTrace();
            }
        }

    }

    public static Connection getConnection() {
        Connection connection = connectionList.get(num);
        num++;
        return connection;
    }

    public static void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
